# _*_ coding:utf-8 _*_
# @Time  : 2023.04.04
# @Author: zizlee
import pathlib
import shutil
from v1_all_api.all_utils import doc_covert
from db import FAConnection


def get_module_need_quote(module_name: str):
    return {
        'Lecture': 10000,
        'Accompany': 8000,
        'InvestmentPlan': 5000,
        'Hedging': 6000,
        'CustomerOnline': 5000,
        'AnalysisReport': 0,
        'PPTCourseware': 0,
        'DataNeed': 5000,
        'WxGroup': 20000,
        'WindRemote': 0,
        'Ruizhi': 5000,
        'Zhenduan': 0,
        'Shouquan': 6000
    }.get(module_name)


def get_module_name(module_name: str):
    return {
        'Lecture': '演讲培训',
        'Accompany': '陪同走访',
        'InvestmentPlan': '投资计划',
        'Hedging': '套保方案',
        'CustomerOnline': '客户微信群服务',
        'AnalysisReport': '分析报告',
        'PPTCourseware': 'PPT课件',
        'DataNeed': '材料需求',
        'WxGroup': '微信沟通平台',
        'WindRemote': 'wind远程',
        'Ruizhi': '瑞智系统试用',
        'Zhenduan': '期易通交易诊断'
    }.get(module_name)


# 查询当前用户是否够积分申请
def quota_information(module_name: str, user_id: int):
    need_quota = get_module_need_quote(module_name)
    if not need_quota:
        return 999999, 0
    with FAConnection() as cursor:
        cursor.execute('SELECT id,user_id,quota_remain FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT 1;',
                       (user_id, ))
        _quota = cursor.fetchone()
    if not _quota:
        return need_quota, 0
    return need_quota, _quota['quota_remain']


# 积分变化
def quota_change_log(user_id: int, prse_id: int, cursor=None, change: int = 0, module_key: str = '', ):
    cursor.execute('SELECT quota_remain FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT 1;',
                   [user_id])
    remain_ = cursor.fetchone()
    if not remain_:
        remain_quota = 0
    else:
        remain_quota = remain_['quota_remain']
    now_remain = remain_quota - change
    sql = """
        INSERT INTO ruizy_user_quota (user_id,module_name,module_id,description,quota_change,quota_remain)
        VALUES (%s,%s,%s,%s,%s,%s);
    """
    if change >= 0:
        desc = '申请【{}】消耗【{}】'.format(get_module_name(module_key), change)
    else:
        desc = '申请【{}】已拒绝，退回【{}】'.format(get_module_name(module_key), -change)
    cursor.execute(sql, [user_id, module_key, prse_id, desc, change, now_remain])


# 转换任务：将上传的文件转为图片
def covert_file2image(annex_file: pathlib.Path):
    preview_folder = annex_file.parent.joinpath(annex_file.name + 'img')
    # 不存在，就得转化
    if not preview_folder.exists():
        preview_folder.mkdir(parents=True)
    if annex_file.name.endswith('.doc') or annex_file.name.endswith('.docx'):
        # 转为pdf
        pdf_filename = annex_file.name.replace('.docx', '.pdf').replace('.doc', '.pdf')
        pdf_file = annex_file.parent.joinpath(pdf_filename)
        pdf_file_tmp = doc_covert.docx2pdf(str(annex_file), pdf_file)
        # 转为images
        images = doc_covert.pdf2image(pdf_file_tmp, preview_folder)
        if pdf_file.exists() and pdf_file.is_file():
            pdf_file.unlink()
    elif annex_file.name.endswith('.ppt') or annex_file.name.endswith('.pptx'):
        if preview_folder.exists():
            shutil.rmtree(preview_folder, ignore_errors=True)
        images = doc_covert.ppt2pdf(annex_file, preview_folder, is_image=True)
    elif annex_file.name.endswith('.pdf'):
        images = doc_covert.pdf2image(annex_file, preview_folder)
    else:
        return []
    return images
